package summer.tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        LinkedList<TreeNode> queue = new LinkedList<>();
        List<Integer> res = new ArrayList<>();
        if (root != null) queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.getLast();
            if (node != null) {
                queue.removeLast();
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);
                queue.add(node);
                queue.add(null);
            } else {
                queue.removeLast();
                node = queue.removeLast();
                res.add(node.val);
            }
        }
        return res;
    }
}

public class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}